import { FC, useState, useEffect } from 'react';
import ApiCollector from '@/const/apis';
import useMockRequest from '@/hooks/useMockRequest';
import styles from './index.module.less';
import Tabbar from '@/components/tabbar';
import get from 'lodash/get';
import HomeLoader from '@/components/skeleton/homeLoader';
import { useNavigate } from 'react-router';
import Layout from '@/components/layout';
import ComNavBar from '@/components/comNavBar';
import Lines from '@/components/echarts';
import big from '@/images/big.png';
import small from '@/images/small.png';
import magicStore from '@/store/magic';
import { observer } from 'mobx-react-lite'
import { returnFloat,returnFloatTime } from '@/utils/tool';

const grid = {
    top: "30%",
    bottom: '5%',
    left: '1%',
    right: '4%',
}
const gridFull = {
    top: "15%",
    bottom: '10%',
    left: '5%',
    right: '5%',
}

const Home = () => {
    const navigate = useNavigate();
    const [fullScreenOpenOrClose, setFullScreenOpenOrClose] = useState(false)
    const [currentData, setCurrentData] = useState()
    const [currentType, setCurrentType] = useState(1)
    const [homeCardData, setHomeCardData] = useState({})
    // const [lineFormatter, setLineFormatter] = useState('分')
    const [chartSize, setChartSize] = useState(null);

    const [jkdList, setJkdList] = useState({});//健康度趋势图
    const [yhtyList, setYhtyList] = useState({});//用户体验趋势图
    const [xysjList, setXysjList] = useState({});//响应时间趋势图
    const [kylList, setKylList] = useState({});//可用率趋势图


    const szqs = {
        1: ApiCollector.getJkdSzqs,
        2: ApiCollector.getTydSzqs,
        3: ApiCollector.getXysjSzqs,
        4: ApiCollector.getKylSzqs,
    }

    const lineFormatterList = {
        1:"分",
        2:"%",
        3:"ms",
        4:"%"
    }

    // const getUserMenuPermission = useMockRequest(ApiCollector.getUserMenuPermission, {
    //     data: { ...activeCheck },
    //     config: { 
    //         onSuccess: (result, params) => {

    //         }
    //      }
    // });

    const { data, error, loading, run } = useMockRequest(szqs[currentType], {
        config: {
            manual: true,
            refreshDeps: [currentType],
            onSuccess: (result, params) => {
                const data = get(result, 'data.result', [])
                let valuesPreWeek = []
                let valuesThisWeek = []
                if (currentType !== 3) {
                    if (data.valuesPreWeek?.length) {
                        data.valuesPreWeek.map(item => {
                            valuesPreWeek.push(returnFloat(item))
                        })
                    }
                    if (data.valuesThisWeek?.length) {
                        data.valuesThisWeek.map(item => {
                            valuesThisWeek.push(returnFloat(item))
                        })
                    }
                    setCurrentData({
                        ...data,
                        lineData: [
                            { name: '本周', value: valuesThisWeek },
                            { name: '上周', value: valuesPreWeek },
                        ],
                    })
                } else {
                    valuesThisWeek = get(data, 'valuesThisWeek', []).map(item => {
                        return returnFloatTime(item)
                    })
                    valuesPreWeek = get(data, 'valuesPreWeek', []).map(item => {
                        return returnFloatTime(item)
                    })
                    setCurrentData({
                        ...data,
                        xAxis: data.xAxis ? data.xAxis : ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                        lineData: [
                            { name: '本周', value: [...valuesThisWeek] },
                            { name: '上周', value: [...valuesPreWeek] }
                        ]
                    })
                }

            }
        }
    });
    
    const getJkdSrqsRequest = useMockRequest(ApiCollector.getJkdSzqs, {
        // config: {
        //     onSuccess: (result, params) => {
        //         const data = get(result, 'data.result', [])
        //         let valuesPreWeek = []
        //         let valuesThisWeek = []
        //         //趋势图
        //         if (data.valuesPreWeek?.length) {
        //             data.valuesPreWeek.map(item => {
        //                 valuesPreWeek.push(returnFloat(item))
        //             })
        //         }
        //         if (data.valuesThisWeek?.length) {
        //             data.valuesThisWeek.map(item => {
        //                 valuesThisWeek.push(returnFloat(item))
        //             })
        //         }
        //         setCurrentData({
        //             ...data,
        //             lineData: [
        //                 { name: '本周', value: valuesThisWeek },
        //                 { name: '上周', value: valuesPreWeek },
        //             ],
        //         })
        //         setJkdList({
        //             ...data,
        //             lineData: [
        //                 { name: '本周', value: valuesThisWeek },
        //                 { name: '上周', value: valuesPreWeek },
        //             ],
        //         })
        //         //指标值
               
        //         const _data = get(data, 'valuesThisWeek', [])
        //         let newData = [];
        //         _data && _data.length && _data.map(item => {
        //             if(item !== null){
        //                 newData.push(item)
        //             }
        //         })
        //         let _value = null
        //         if (newData && newData.length) {
        //             _value = newData[newData.length - 1]
        //         }
        //         setHomeCardData(pre => ({
        //             ...pre,
        //             getJkdSzqs: returnFloat(_value)
        //         }))
        //     }
        // }
    });
    // const getJkdSrqsRequest = useMockRequest(ApiCollector.getJkdSrqs, {
    //     config: {
    //         onSuccess: (result, params) => {
    //             const data = get(result, 'data.result', [])
    //             const _data = get(data, 'valuesToday', [])
    //             let newData = [];
    //             _data && _data.length && _data.map(item => {
    //                 if(item !== null){
    //                     newData.push(item)
    //                 }
    //             })
    //             let _value = null
    //             if (newData && newData.length) {
    //                 _value = newData[newData.length - 1]
    //             }
    //             setHomeCardData(pre => ({
    //                 ...pre,
    //                 getJkdSrqs: returnFloat(_value)
    //             }))
    //         }
    //     }
    // });
    const getTydSrqsRequest = useMockRequest(ApiCollector.getTydSzqs, {
        config: {
            onSuccess: (result, params) => {
                const data = get(result, 'data.result', [])
                let valuesPreWeek = []
                let valuesThisWeek = []
                //趋势图
                if (data.valuesPreWeek?.length) {
                    data.valuesPreWeek.map(item => {
                        valuesPreWeek.push(returnFloat(item))
                    })
                }
                if (data.valuesThisWeek?.length) {
                    data.valuesThisWeek.map(item => {
                        valuesThisWeek.push(returnFloat(item))
                    })
                }
                setCurrentData({
                    ...data,
                    lineData: [
                        { name: '本周', value: valuesThisWeek },
                        { name: '上周', value: valuesPreWeek },
                    ],
                })
                setYhtyList({
                    ...data,
                    lineData: [
                        { name: '本周', value: valuesThisWeek },
                        { name: '上周', value: valuesPreWeek },
                    ],
                })
                //指标值
                
                const _data = get(data, 'valuesThisWeek', [])
                let newData = [];
                _data && _data.length && _data.map(item => {
                    if(item !== null){
                        newData.push(item)
                    }
                })
                let _value = null
                if (newData && newData.length) {
                    _value = newData[newData.length - 1]
                }
                setHomeCardData(pre => ({
                    ...pre,
                    getTydSzqs: returnFloat(_value)
                }))
            }
        }
    });
    // const getTydSrqsRequest = useMockRequest(ApiCollector.getTydSrqs, {
    //     config: {
    //         onSuccess: (result, params) => {
    //             const data = get(result, 'data.result', [])
    //             const _data = get(data, 'valuesToday', [])
    //             let newData = [];
    //             _data && _data.length && _data.map(item => {
    //                 if(item !== null){
    //                     newData.push(item)
    //                 }
    //             })
    //             let _value = null
    //             if (newData && newData.length) {
    //                 _value = newData[newData.length - 1]
    //             }
    //             setHomeCardData(pre => ({
    //                 ...pre,
    //                 getTydSrqs: returnFloat(_value)
    //             }))
    //         }
    //     }
    // });
    const getKylSrqsRequest = useMockRequest(ApiCollector.getKylSzqs, {
        config: {
            onSuccess: (result, params) => {
                const data = get(result, 'data.result', [])
                let valuesPreWeek = []
                let valuesThisWeek = []
                //趋势图
                if (data.valuesPreWeek?.length) {
                    data.valuesPreWeek.map(item => {
                        valuesPreWeek.push(returnFloat(item))
                    })
                }
                if (data.valuesThisWeek?.length) {
                    data.valuesThisWeek.map(item => {
                        valuesThisWeek.push(returnFloat(item))
                    })
                }
                setCurrentData({
                    ...data,
                    lineData: [
                        { name: '本周', value: valuesThisWeek },
                        { name: '上周', value: valuesPreWeek },
                    ],
                })
                setKylList({
                    ...data,
                    lineData: [
                        { name: '本周', value: valuesThisWeek },
                        { name: '上周', value: valuesPreWeek },
                    ],
                })
                //指标值
               
                const _data = get(data, 'valuesThisWeek', [])
                let newData = [];
                _data && _data.length && _data.map(item => {
                    if(item !== null){
                        newData.push(item)
                    }
                })
                let _value = null
                if (newData && newData.length) {
                    _value = newData[newData.length - 1]
                }
                setHomeCardData(pre => ({
                    ...pre,
                    getKylSzqs: returnFloat(_value)
                }))
            }
        }
    });
    // const getKylSrqsRequest = useMockRequest(ApiCollector.getKylSrqs, {
    //     config: {
    //         onSuccess: (result, params) => {
    //             const data = get(result, 'data.result', [])
    //             const _data = get(data, 'valuesToday', [])
    //             let newData = [];
    //             _data && _data.length && _data.map(item => {
    //                 if(item !== null){
    //                     newData.push(item)
    //                 }
    //             })
    //             let _value = null
    //             if (newData && newData.length) {
    //                 _value = newData[newData.length - 1]
    //             }
    //             setHomeCardData(pre => ({
    //                 ...pre,
    //                 getKylSrqs: returnFloat(_value)
    //             }))
    //         }
    //     }
    // });
     //响应时间双周趋势
    const getXySrqsRequest = useMockRequest(ApiCollector.getXysjSzqs, {
        config: {
            onSuccess: (result, params) => {
                const data = get(result, 'data.result', [])
                let valuesPreWeek = []
                let valuesThisWeek = []
                //趋势图
                valuesThisWeek = get(data, 'valuesThisWeek', []).map(item => {
                    return returnFloatTime(item)
                })
                valuesPreWeek = get(data, 'valuesPreWeek', []).map(item => {
                    return returnFloatTime(item)
                })
                setCurrentData({
                    ...data,
                    xAxis: data.xAxis ? data.xAxis : ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                    lineData: [
                        { name: '本周', value: [...valuesThisWeek] },
                        { name: '上周', value: [...valuesPreWeek] }
                    ]
                })
                setXysjList({
                    ...data,
                    xAxis: data.xAxis ? data.xAxis : ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                    lineData: [
                        { name: '本周', value: [...valuesThisWeek] },
                        { name: '上周', value: [...valuesPreWeek] }
                    ]
                })
                //指标值
               
                const _data = get(data, 'valuesThisWeek', [])
                let newData = [];
                _data && _data.length && _data.map(item => {
                    if(item !== null){
                        newData.push(item)
                    }
                })
                let _value = null
                if (newData && newData.length) {
                    _value = newData[newData.length - 1]
                }
                setHomeCardData(pre => ({
                    ...pre,
                    getXysjSzqs: returnFloatTime(_value)
                }))
            }
        }
    });
    //响应时间双日趋势
    // const getXySrqsRequest = useMockRequest(ApiCollector.getXySrqs, {
    //     config: {
    //         onSuccess: (result, params) => {
    //             const data = get(result, 'data.result', [])
    //             const _data = get(data, 'valuesToday', [])
    //             let newData = [];
    //             _data && _data.length && _data.map(item => {
    //                 if(item !== null){
    //                     newData.push(item)
    //                 }
    //             })
    //             let _value = null
    //             if (newData && newData.length) {
    //                 _value = newData[newData.length - 1]
    //             }
    //             setHomeCardData(pre => ({
    //                 ...pre,
    //                 getXySrqs: returnFloatTime(_value)
    //             }))
    //         }
    //     }
    // });

    const getWafyyfhqRequest = useMockRequest(ApiCollector.getWafyyfhq, {
        config: {
            onSuccess: (result, params) => {
                const data = get(result, 'data.result', [])
                setHomeCardData(pre => ({
                    ...pre,
                    getWafyyfhq: {
                        white_list: get(data, 'white_list', ''),
                        deny_list: get(data, 'deny_list', ''),
                        request_total: get(data, 'request_total', ''),
                    }
                }))

            }
        }
    });

    const getAqtsgzRequest = useMockRequest(ApiCollector.getAqtsgz, {
        config: {
            onSuccess: (result, params) => {
                const data = get(result, 'data.result', [])
                setHomeCardData(pre => ({
                    ...pre,
                    getAqtsgz: {
                        attack_failed: get(data, 'attack_failed', ''),
                        attack_total: get(data, 'attack_total', ''),
                        attack_success: get(data, 'attack_success', ''),
                    }
                }))
            }
        }
    });

    const getFwqaqfhRequest = useMockRequest(ApiCollector.getFwqaqfh, {
        config: {
            onSuccess: (result, params) => {
                const data = get(result, 'data.result', [])

                let value = [
                    {
                        intercept_count: "",
                        total: ""
                    },
                    {
                        intercept_count: "",
                        total: ""
                    },
                    {
                        intercept_count: "",
                        total: ""
                    }
                ]
                setHomeCardData(pre => ({
                    ...pre,
                    getFwqaqfh: data && data.length ? data : value
                }))
            }
        }
    });

    useEffect(() => {
        if (currentType) {
            setCurrentData({})
            // run()
        }
    }, [])
    // }, [currentType])

    // if (loading) {
    //     return <div className={styles.loader}>
    //         <HomeLoader />
    //     </div>;
    // }
    const onClickFull = () => {
        setFullScreenOpenOrClose(true)
    }

    const onClickFullClose = () => {
        setFullScreenOpenOrClose(false)
    }

    const toYingyongList = () => {
        navigate('/systemList', { replace: true })
    }

    const onclickToNavigate = (cur) => {
        magicStore.triggerMagic(cur)
        navigate('/safeTaeget', { replace: true })
    }

    const homeCard = () => {
        return <div className={styles.home_system_card}>
            <div className={styles.system_card_item}>
                <div className={styles.card_item_sys} onClick={() => { setCurrentType(1) }}>
                    <div className={styles.card_item_i_value}>{homeCardData.getJkdSzqs}分</div>
                    <div className={styles.card_item_i_name}>系统总健康度</div>
                </div>
                <div className={styles.card_item_yonghu} onClick={() => { setCurrentType(2) }}>
                    <div className={styles.card_item_i_value}>{homeCardData.getTydSzqs}%</div>
                    <div className={styles.card_item_i_name}>用户体验度</div>
                </div>
            </div>
            <div className={styles.system_card_item}>
                <div className={styles.card_item_time} onClick={() => { setCurrentType(3) }}>
                    <div className={styles.card_item_i_value}>{homeCardData.getXysjSzqs}ms</div>
                    <div className={styles.card_item_i_name}>平均响应时间</div>
                </div>
                <div className={styles.card_item_keyong} onClick={() => { setCurrentType(4) }}>
                    <div className={styles.card_item_i_value}>{homeCardData.getKylSzqs}%</div>
                    <div className={styles.card_item_i_name}>系统总可用率</div>
                </div>
            </div>
        </div>
    }

    const carTargetWAF = () => {
        return <div className={styles.carTargetWAF} onClick={() => { onclickToNavigate(0) }}>
            <div className={styles.home_system_title}>WAF应用防火墙(今日数据)</div>
            <div className={styles.carTarget_WAF}>
                <div className={styles.carTarget_WAF_item}>
                    <div className={styles.WAF_item_name}>高危请求数</div>
                    <div className={styles.WAF_item_value}>{get(homeCardData.getWafyyfhq, 'request_total', '')}</div>
                </div>
                <div className={styles.carTarget_WAF_item}>
                    <div className={styles.WAF_item_name}>白名单放行数</div>
                    <div className={styles.WAF_item_value}>{get(homeCardData.getWafyyfhq, 'white_list', '')}</div>
                </div>
                <div className={styles.carTarget_WAF_item}>
                    <div className={styles.WAF_item_name}>拦截数</div>
                    <div className={styles.WAF_item_value}>{get(homeCardData.getWafyyfhq, 'deny_list', '')}</div>
                </div>
            </div>
        </div>
    }

    const carTargetSofe = () => {
        return <div className={styles.carTargetSofe} onClick={() => { onclickToNavigate(1) }}>
            <div className={styles.home_system_title}>安全态势感知(今日数据)</div>
            <div className={styles.carTarget_WAF}>
                <div className={styles.carTarget_WAF_item}>
                    <div className={styles.WAF_item_name}>检测攻击数</div>
                    <div className={styles.WAF_item_value}>{get(homeCardData.getAqtsgz, 'attack_total', '')}</div>
                </div>
                <div className={styles.carTarget_WAF_item}>
                    <div className={styles.WAF_item_name}>攻击成功数</div>
                    <div className={styles.WAF_item_value}>{get(homeCardData.getAqtsgz, 'attack_success', '')}</div>
                </div>
                <div className={styles.carTarget_WAF_item}>
                    <div className={styles.WAF_item_name}>攻击失败数</div>
                    <div className={styles.WAF_item_value}>{get(homeCardData.getAqtsgz, 'attack_failed', '')}</div>
                </div>
            </div>
        </div>
    }

    const carTargetSQL = () => {
        let targetValue = get(homeCardData, 'getFwqaqfh', [])
        let targetLen = targetValue.length > 0
        return <div className={styles.carTargetSQL} onClick={() => { onclickToNavigate(2) }}>
            <div className={styles.home_system_title}>服务器安全防护(今日数据)</div>
            <div className={styles.carTarget_WAF}>
                <div className={styles.carTarget_WAF_item}>
                    <div className={styles.WAF_item_name}>恶意软件事件</div>
                    <div className={styles.WAF_item_value}>{targetLen && targetValue[0]?.intercept_count}/{targetLen && targetValue[0]?.total}</div>
                    <div className={styles.WAF_item_value}>(拦截数/总数)</div>
                </div>
                <div className={styles.carTarget_WAF_item}>
                    <div className={styles.WAF_item_name}>防火墙事件</div>
                    <div className={styles.WAF_item_value}>{targetLen && targetValue[1]?.intercept_count}/{targetLen && targetValue[1]?.total}</div>
                    <div className={styles.WAF_item_value}>(拦截数/总数)</div>
                </div>
                <div className={styles.carTarget_WAF_item}>
                    <div className={styles.WAF_item_name}>IPS事件</div>
                    <div className={styles.WAF_item_value}>{targetLen && targetValue[2]?.intercept_count}/{targetLen && targetValue[2]?.total}</div>
                    <div className={styles.WAF_item_value}>(拦截数/总数)</div>
                </div>
            </div>
        </div>
    }

    useEffect(() => {
        const handleResize = () => {
          const canvas = document.getElementById("homeLineBox");
          setChartSize({
            width: canvas.offsetWidth,
            height: canvas.offsetHeight
          });
        };
      
        window.addEventListener("resize", handleResize);
        handleResize();
      
        return () => {
          window.removeEventListener("resize", handleResize);
        };
      }, []);
    return <Layout title="陕汽核心系统移动端监控" navbar={true}>
        {fullScreenOpenOrClose ? <div className={styles.fullScreen}>
            <div className={styles.sysResponseTime_top}>
                <div className={styles.sysResponseTime_top_img} onClick={() => { onClickFullClose() }}><img src={small} style={{ width: "100%", height: "100%" }} /></div>
            </div>
            <Lines part={true} unit={currentType == 3 ? '' :'%'}  data={currentType == 1 ? jkdList : currentType == 2 ? yhtyList : currentType == 3 ? xysjList : kylList} xAxisInterval={currentType == 3 ? 1 : 0} splitLineShow={true} grid={gridFull} yAxisPosition={'left'} tooltipShow={true} yAxisName={`单位 ${lineFormatterList[currentType]}`}/>
        </div> :
            <div className={styles.bg}>
                <ComNavBar title={'陕汽核心系统移动端监控'} />
                <div className={styles.carTabs}>
                    <div className={styles.home_system}>
                        <div className={styles.home_system_title}>系统指标</div>
                        {homeCard()}
                        <div className={styles.home_system_echarts} id="homeLineBox">
                            <div className={styles.home_system_echarts_img} onClick={() => { onClickFull() }}><img src={big} style={{ width: "100%", height: "100%" }} /></div>
                            {/* {chartSize && chartSize.width > 0 && currentData && !loading && <Lines part={true} chartSize={chartSize}  data={currentData} xAxisInterval={0} splitLineShow={true} grid={grid} yAxisPosition={'left'} tooltipShow={true} yAxisName={`单位 ${lineFormatterList[currentType]}`}/>} */}
                            {chartSize && chartSize.width > 0 && currentData && !loading && <Lines unit={currentType == 3 ? '' :'%'} part={true} chartSize={chartSize}  data={currentType == 1 ? jkdList : currentType == 2 ? yhtyList : currentType == 3 ? xysjList : kylList} xAxisInterval={0} splitLineShow={true} grid={grid} yAxisPosition={'left'} tooltipShow={true} yAxisName={`单位 ${lineFormatterList[currentType]}`}/>}

                        </div>
                        <div className={styles.to_system_btn} onClick={() => { toYingyongList() }}>查看所有应用系统</div>

                    </div>
                </div>
                {carTargetWAF()}
                {carTargetSofe()}
                {carTargetSQL()}

            </div>
        }
    </Layout>;

};

export default observer(Home);


